// mircoApp/tiktok_writeoff/index/index.js
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');
import util from "../../../utils/util.js";
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [skinBehavior],
  data: {
    pre_id:"",
    activity_count:0,
    order_deductions:[],
    arr: [],
    info:{},
    form_id:"",
    activity:{},
    total_price:0,
    form_data_id:"",
    orderId:"",
    payStatus: "",
    applyStatus: "",
    activity_info: [],
    activityId: "",


    plugin_id: "",
    isNew: null,
    form: {
      name: "",
      domain: "",
      mobile: "",
      code: "",
    },
    domain: "",
    count: 0,
    timer: null,
    show_domain: true,
    domain_show: false,


    store_id:"",
    status: 1,
    loading: false,

    _show_address: false,
    realname: "",
    mobile: "",
    address: "",

    showAddressList: false,
    show_add_address: true,


    showKefu: false,
    cservice: "",
    service_mobile: "",
    service_QRcode: "",

    polygons_2: [{
      points: [],
      fillColor: "#FF88887F",
      strokeColor: "#FFF",
      strokeWidth: 2,
      zIndex: 1,
    }],
    delivery_status: 1,
    selected: 0,


    Height: 0,
    LastHeight: 0,

    rotation: [],
    introduce: "",
    verify_token: "",
    _currentAddress: {},
    is_show_address: false,

    id: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split("&");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "m") {
            app._setMid(chil_arr[1])
          } else if (chil_arr[0] == "id") {
            this.setData({
              id: chil_arr[1],
            });
          }
        }
      }
    }else if(options.id){
      this.setData({id:options.id});
    }else if(options.store_id){
      this.setData({store_id:options.store_id})
    }
    this.setData({activity:""})

    this.getKefu();
    this.getData();
    this.setData({
      domain: app.data.host.match(/https:\/\/(\S*)\//)[1],
    });
  },
  loadimg(e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    var swiperH =
      (winWid * imgh) /
      (imgw); //等比设置swiper的高度。 即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度  ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    if (parseInt(swiperH) > this.data.LastHeight) {
      this.setData({
        Height: swiperH, //设置高度
      });
      this.data.LastHeight = parseInt(swiperH);
    }
  },
  sureIdentify() {
    let that = this;
    let form = this.data.form;
    if (app._isTextEmpty(form.mobile)) {
      app.tips("请先填写手机号", "none", 1000);
      return;
    }
    let json = {
      mobile: that.data.form.mobile,
    };
    const TIME_COUNT = 60;
    // let uid = wx.getStorageSync('uid');
    that.data.count = TIME_COUNT;
    let url = "plugin.product-market.api.client.index.send-code";
    if (this.data.plugin_id == 58) {
      url = "plugin.market-sub.api.client.index.send-code";
    }
    let urlStr = app.getNetAddresss(url);
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        if (res.result == 1) {
          app.tips("已发送", "none", 1500);
          that.data.timer = setInterval(() => {
            if (that.data.count > 0 && that.data.count <= TIME_COUNT) {
              that.setData({
                count: that.data.count - 1,
              });
            } else {
              clearInterval(that.data.timer);
              that.data.timer = null;
            }
          }, 1000);
        } else {
          app.tips(res.msg, "none", 1500);
        }
      },
      fail: function (res) {
        console.log(res);
        wx.hideLoading({
          complete: (res) => {},
        });
      },
    });
  },
  checkDomain() {
    if (this.data.form.domain.indexOf("https://") > -1 || this.data.form.domain.indexOf("http://") > -1) {
      return false;
    }
    return true;
  },
  toSave(e) {
    if (this.checkIn()) {
      let url = "";
      if (this.data.isNew) {
        url = "plugin.product-market.api.client.index.add";
        if (this.data.plugin_id == 58) {
          url = "plugin.market-sub.api.client.index.add";
        }
      } else {
        url = "plugin.product-market.api.client.index.bind";
        if (this.data.plugin_id == 58) {
          url = "plugin.market-sub.api.client.index.bind";
        }
      }
      let urlStr = app.getNetAddresss(url);
      app._postNetWork({
        url: urlStr,
        data: this.data.form,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 1000,
              success: function () {
                this.reload_data();
              },
            });
          } else {
            app.tips(res.msg, "none", 1500);
          }
        },
        fail: function () {},
      });
    }
  },
  priceChange() {
    let urlStr = app.getNetAddresss("order.goods-buy");
    let that = this;
    let json = {
      address: JSON.stringify({}),
      dispatch_type_id: 0,
      goods_id: this.data.activity.goods_id,
      total:1,
      option_id: "",
      orders: JSON.stringify([]),
      member_coupon_ids: "",
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          if (res.data.discount && res.data.discount.default_deduction && res.data.discount.default_deduction != 0) {
            // 获取第一次接口默认积分抵扣
            this.data.default_deduction = res.data.discount.default_deduction;
          }
          that.setData({
            total_price: res.data.total_price,
            pre_id: res.data.orders[0].pre_id,
            order_deductions: res.data.orders[0].order_deductions,
          });
          for (let val in that.data.order_deductions) {
            if (that.data.order_deductions[val].code == "point" && that.data.order_deductions[val].checked == true) {
              let arrs = [];
              arrs.push("point");
              that.setData({arr: arrs});
            }
          }
          let info = {
            orders: JSON.stringify([
              {
                deduction_ids: that.data.arr,
                pre_id: that.data.pre_id,
              },
            ]),
            dispatch_type_id: 0,
            activity_id: that.data.activity_id,
            test_uid: wx.getStorageSync("uid"),
            lecturer_id: that.data.activity.lecturer_id,
            calssify_id: that.data.activity.calssify_id,
            goods: JSON.stringify([
              {
                goods_id: that.data.activity.goods_id,
                total: that.data.num,
                option_id: 0,
              },
            ]),
            form_id: "",
          };
          that.setData({
            info: info,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  reload_data(){
    this.get_prepare();
    this.setData({domain_show:false});
  },
  checkIn() {
    if (this.data.isNew && app._isTextEmpty(this.data.form.name)) {
      app.tips("请填写公司/个人名称", "none", 1000);
      return false;
    }
    if (app._isTextEmpty(this.data.form.domain)) {
      app.tips("请填写域名", "none", 1000);
      return false;
    }
    if (!this.checkDomain()) {
      wx.showModal({
        title: "提示",
        content: "域名格式不正确: 请填写没有https://或http:// 格式的域名",
        showCancel: false,
        success(res) {},
      });
      return false;
    }
    if (app._isTextEmpty(this.data.form.mobile)) {
      app.tips("请填写手机号码", "none", 1000);
      return false;
    }
    if (app._isTextEmpty(this.data.form.code)) {
      app.tips("请输入验证码", "none", 1000);
      return false;
    }

    return true;
  },
  onClose(e) {
    let num = e.currentTarget.dataset.filed;
    if (num == 1) {
      this.setData({domain_show: false});
    }else{
      this.setData({diyforms_show:false});
    }
  },

  postForm(e) {
    console.log(e,'============来这里',this.data.activity_count >= this.data.activity.limit);
    // 更新
    let json = {
      form_id: this.data.form_id,
      form_data: e.detail,
    };
    if (this.data.activity_count >= this.data.activity.limit) {
      wx.showToast({
        title: "报名人数已超过限制",
        icon: "none",
        duration: 1000,
      });
      return;
    }
    let that = this;
    let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.save-diy-form-data");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            "info.form_id": res.data.form_data_id,
            "info.activity_id":that.data.activityId
          });
          that.toNew();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {},
    });
  },
  toNew() {
    let that = this;
    let json = {
      form_data_id: this.data.info.form_id,
      activity_id: this.data.activityId,
      form_id: this.data.activity.form_id,
    };
    console.log(json);
    let urlStr = app.getNetAddresss("plugin.activity-apply.api.Activity.getDiyForm");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.notfree(that.data.info);
        } else {
          wx.showToast({
            title: res.msg,
            duration: 500,
            icon: "none",
          });
        }
      },
    });
  },
  notfree(info){
    let urlStr = app.getNetAddresss("plugin.activity-apply.api.create");
    app._postNetWork({
      url: urlStr,
      data: info,
      success:  (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          this.get_prepare();
          this.setData({diyforms_show:false});
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: '1000'
          });
        }
      },
      fail: function (res) {

      }
    });
  },
  on_before_enter(e) {
    let num = e.currentTarget.dataset.filed;
    if (num == 1) {
      this.checkData()
    }else{
      this.test()
    }
  },
  test(){
    let urlStr = app.getNetAddresss("plugin.activity-apply.api.Activity.getActivityEnrol");
    app._getNetWork({
      url: urlStr,
      data: {
        activity_id: this.data.activityId,
      },
      success:  (resdata)=> {
        var res = resdata.data;
        if(res.data&&res.data.enrol == 2){
          //添加权限
          app.tips(res.msg);
          return false
        }
        if (res.result == 1) {
          this.setData({ payStatus: res.data.enrol,applyStatus: res.data.status});
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
          this.getlist();
        } else {
          this.setData({ payStatus: 0});
          this.getlist();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
    // 获取报名详情
    getlist() {
      let urlStr = app.getNetAddresss("plugin.activity-apply.api.Activity.getActivity");
      app._getNetWork({
        url: urlStr,
        data: {
          activity_id: this.data.activityId,
        },
        success:  (resdata) =>{
          var res = resdata.data;
          if (res.result == 1) {
            res.data.start_time = util.formatTimeTwo(res.data.start_time, "Y/M/D h:m:s");
            res.data.end_time = util.formatTimeTwo(res.data.end_time, "Y/M/D h:m:s");
            let data = res.data;
            let activity_count = data.has_many_pay_order.length > 0 ? data.has_many_pay_order[0].count:0;
            console.log(data,"data=====")
            this.setData({
              activity: data,
              form_id: data.form_id,
              total_price:data.cash,
              activity_count
            });
            let orderIds = this.data.activity.has_many_pay_order.length > 0 ? this.data.activity.has_many_pay_order[0].order_id : "";
            let fromDataId = !app._isTextEmpty(this.data.activity.form_data_id) ? this.data.activity.form_data_id.form_data_id : "";
            this.setData({
              orderId: orderIds,
              // form_data_id: fromDataId,
            });
            if (Number(res.data.cash) > 0) {
              this.priceChange();
            } else {
              let infos = {
                dispatch_type_id: 0,
                activity_id: this.data.activity_id,
                test_uid: wx.getStorageSync("uid"),
                lecturer_id: this.data.activity.lecturer_id,
                calssify_id: this.data.activity.calssify_id,
                goods: JSON.stringify([
                  {
                    goods_id: this.data.activity.goods_id,
                    total: this.data.num,
                    option_id: 0,
                  },
                ]),
                form_id: "",
              };
              this.setData({
                info: infos,
              });
            }
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
  toChange(e) {
    let str = e.currentTarget.dataset.new;
    if (str == "new") {
      this.data.isNew = 1
    } else {
      this.data.isNew = 2
    }
    this.setData({
      show_domain: false,
      isNew: this.data.isNew
    })
  },
  checkData() {
    let url = "plugin.product-market.api.client.index";
    console.log(this.data.plugin_id)
    if (this.data.plugin_id == 58) {
      url = "plugin.market-sub.api.client.index";
    }
    let urlStr = app.getNetAddresss(url);
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result != 1) {
          wx.showModal({
            title: "提示",
            content: res.msg,
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1,
                });
              }
            },
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getKefu() {
    app._getNetWork({
      url: app.getNetAddresss("plugin.tiktok-verify-ticket.api.verify.customer-service"),
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        this.setData({
          service_mobile: data.service_mobile,
          service_QRcode: data.service_QRcode,
          service: data.cservice
        })
      }
    })
  },
  getData() {
    app._getNetWork({
      url: app.getNetAddresss("plugin.tiktok-verify-ticket.api.verify.index"),
      data: {
        id: this.data.id
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        this.setData({
          rotation: data.rotation,
          introduce: data.introduce
        })
      }
    });

  },
  banner_link(e) {
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    })
  },

  confirmSelectAddress(e) {
    let info;
    if (e.detail.loc) {
      info = e.detail.form;
    } else {
      info = e.detail;
    }
    this._setAddressViewData(info);
    this.setData({
      _currentAddress: e.detail,
      showAddressList: false,
    });
  },

  //设置地址界面
  _setAddressViewData(model) {
    if (model == undefined || model == "" || model == []) {
      return;
    }

    if (this.options.tag === "cake") {
      this.setData({
        cakeCity: model.city,
        shopDetail: '',
        shopName: '',
        shopId: ''
      });
      this.getRule();
    }

    //设置地址id
    this.data.currentAddId = model.id || model.address_id;
    this.setData({
      currentAddress: model,
      realname: app._isTextEmpty(model.username) ? "" : model.username,
      mobile: app._isTextEmpty(model.mobile) ? "" : model.mobile,
      address: app._isTextEmpty(model.province) ? (model.address ? model.address : "") : model.province + " " + model.city + " " + model.district + " " + (app._isTextEmpty(model.street) ? "" : model.street + " ") + model.address,
    });
  },
  showAddress(e) {
    if (this.data.status == 3) {
      return;
    }
    //获取收货地址
    this.setData({
      showAddressList: true
    });
    if (this.data.showAddressList) {
      let address = this.selectComponent('#yz_showAddressShop');
      address.setData({
        add_address: this.data.show_add_address
      })
    }
  },
  InputHandle(e) {
    this.setData({
      code: e.detail
    })
  },
  get_prepare(){
    let  json = {
      code: this.data.code,
      id: this.data.id,
    }
    this.setData({ loading: true});
    app._postNetWork({
      url: app.getNetAddresss('plugin.tiktok-verify-ticket.api.verify.prepare'),
      data: json,
      success: resdata => {
        let { result,msg,data} = resdata.data;
        this.setData({loading: false})
        if (result !== 1) {
          return app.tips(msg);
        }
        this.setData({
          status: 2,
          right: data.right,
          verify_token: data.verify_token,
          encrypted_code: data.encrypted_code,
          activity_info:data.activity_info,
          has_domain:data.has_domain
        });
        if (data.need_address) {
          this.setData({is_show_address: true});
          if (data.default_address) {
            this.setData({
              _currentAddress: data.default_address,
              realname: data.default_address.username,
              mobile: data.default_address.mobile,
              address: `${data.default_address.province} ${data.default_address.city} ${data.default_address.district} ${data.default_address.address}`
            })
          } else {
            this.getAddress();
          }
        } else {
          this.setData({
            is_show_address: false
          })
        }

      }
    })
  },
  check(e) {
    if (this.data.loading) {
      return;
    }
    let status = e.currentTarget.dataset.status;
    let _url = '',
      json = {};
    if (status == 1) {
      this.get_prepare();
    } else if (status == 2) {
      _url = 'plugin.tiktok-verify-ticket.api.verify.startVerify';
      json = {
        encrypted_code: this.data.encrypted_code,
        code: this.data.code,
        verify_token: this.data.verify_token,
        id:this.data.id
      }
      if(this.data.store_id){
        json.shop_id=this.data.store_id;
      }
      if (this.data.is_show_address) {
        if (JSON.stringify(this.data._currentAddress) == "{}") {
          return app.tips("请选择地址")
        }
        json.address = encodeURIComponent(JSON.stringify(this.data._currentAddress))
      }

      if (this.chek_goods_type()) {
        this.setData({
          loading: true
        })
        app._postNetWork({
          url: app.getNetAddresss(_url),
          data: json,
          success: resdata => {
            let {result, msg, data } = resdata.data;
            this.setData({ loading: false});
            app.tips(msg);
            if (result == 1) {
              this.selectComponent("#equity").get_order(data.id);
              this.setData({ status: 3 });
            }
          }
        })
      }
    }

  },

  chek_goods_type() {
    let result = this.data.activity_info.filter(item => {
      if (!item.has_sign) {
        return item;
      }
    })
    if (result && result.length !== 0) {
      this.setData({
        activityId: result[0].id,
        diyforms_show: true
      })
      return false
    } else {
      for (let j = 0; j < this.data.right.good.length; j++) {
        if (this.data.right.good[j].plugin_id === 58) {
          this.setData({
            plugin_id: 58
          })
        }
      }
      //为空时代表有应用市场或应用市场子平台上单，并且没有绑定站点
      if (this.data.has_domain !== null && this.data.has_domain == '') {
        this.setData({
          domain_show: true
        })
        return false
      }
    }
    return true;
  },

  getAddress() {
    app._postNetWork({
      url: app.getNetAddresss("member.member-address.index"),
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        let _address = data.filter(function (item) {
          return item.isdefault === 1;
        });
        let realname = _address[0].username;
        let mobile = _address[0].mobile;
        let address = `${_address[0].province} ${_address[0].city} ${_address[0].district} ${_address[0].street || ''} ${_address[0].address}`
        this.setData({
          _show_address: false,
          address,
          mobile,
          realname,
          _currentAddress: _address[0]
        })
      }

    });

  },
  goto() {
    wx.navigateTo({
      url: "/mircoApp/tiktok_writeoff/record/record"
    })
  },
  kefu_handle() {
    this.setData({
      showKefu: true
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  tel(e) {
    this.setData({
      "form.mobile": e.detail,
    });
  },
  domain(e) {
    this.setData({
      "form.domain": e.detail,
    });
  },
  company(e) {
    this.setData({
      "form.name": e.detail,
    });
  },
  auth(e) {
    this.setData({
      "form.code": e.detail,
    });
  },
})